//
//  WKRegisterVC.m
//  WuKongLogin
//
//  Created by tt on 2020/6/18.
//

#import "WKRegisterVC.h"
#import "WKRegisterVM.h"
#import "WKLoginVC.h"
#import <M80AttributedLabel/M80AttributedLabel.h>
#import "WKUsernameLoginVM.h"
#import "WKMnemonicsVC.h"
#import "WKMnemonicsBackupVC.h"
typedef enum : NSUInteger {
    CodeStatusNormal, // 正常
    CodeStatusGeting, // 获取中
    CodeStatusCountdown // 倒计时中
} CodeStatus;

static int lastGetCodeTimestamp = 0; // 最后一次获取验证码的时间戳（单位秒）

@interface WKRegisterVC ()<UITextFieldDelegate,M80AttributedLabelDelegate>


@property(nonatomic,strong) UIImageView *bgImgView; // 背景图
@property(nonatomic,strong) UILabel *titleLbl; // 欢迎标题

// ---------- 用户名输入相关 ----------
@property(nonatomic,strong) UILabel *usernameLbl;
@property(nonatomic,strong) UIView *usernameBoxView; // 用户名输入的box view
@property(nonatomic,strong) UITextField *usernameTextField; // 手机输入
@property(nonatomic,strong) UIView *usernameBottomLineView; // 用户名底部输入线


// ---------- 密码输入相关 ----------
@property(nonatomic,strong) UILabel *passwordLbl;
@property(nonatomic,strong) UIView *passwordBoxView; // 密码输入的box view
@property(nonatomic,strong) UIView *passwordBottomLineView; // 密码底部输入线
@property(nonatomic,strong) UITextField *passwordTextField; // 密码输入
@property(nonatomic,strong) UIButton *eyeBtn; // 眼睛关闭

// ---------- 昵称输入相关 ----------
@property(nonatomic,strong) UILabel *nicknameLbl;
@property(nonatomic,strong) UIView *nicknameBoxView; // 昵称输入的box view
@property(nonatomic,strong) UIView *nicknameBottomLineView; // 昵称底部输入线
@property(nonatomic,strong) UITextField *nicknameTextField; // 昵称输入

// ---------- 底部相关 ----------
@property(nonatomic,strong) UIButton *registerBtn; // 注册按钮
@property(nonatomic,strong) UILabel *loginTipLbl; // 登录提示
@property(nonatomic,strong) UIButton *toLoginBtn; // 去登录

@property(nonatomic,strong) M80AttributedLabel *privacyLbl; // 隐私条款

@end

@implementation WKRegisterVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.viewModel = [WKRegisterVM new];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationBar.hidden = YES;
    [self.view addSubview:self.bgImgView];
    [self.view addSubview:self.titleLbl];
    
    // username
    [self.view addSubview:self.usernameBoxView];
    [self.usernameBoxView addSubview:self.usernameLbl];
    [self.usernameBoxView addSubview:self.usernameTextField];
    [self.usernameBoxView addSubview:self.usernameBottomLineView];
    
    // password
    [self.view addSubview:self.passwordBoxView];
    [self.passwordBoxView addSubview:self.passwordLbl];
    [self.passwordBoxView addSubview:self.passwordBottomLineView];
    [self.passwordBoxView addSubview:self.passwordTextField];
    [self.passwordBoxView addSubview:self.eyeBtn];
    
    // nickname
    [self.view addSubview:self.nicknameBoxView];
    [self.nicknameBoxView addSubview:self.nicknameLbl];
    [self.nicknameBoxView addSubview:self.nicknameTextField];
    [self.nicknameBoxView addSubview:self.nicknameBottomLineView];
    
    [self.view addSubview:self.registerBtn];
    [self.view addSubview:self.loginTipLbl];
    [self.view addSubview:self.toLoginBtn];
    
    [self.view addSubview:self.privacyLbl];
    
}

- (WKBaseVM *)viewModel {
    return [WKRegisterVM new];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}


#pragma mark -- 视图初始化

// ---------- 背景图片 ----------
- (UIImageView *)bgImgView {
    if(!_bgImgView) {
        _bgImgView = [[UIImageView alloc] initWithImage:[[WKApp shared] loadImage:@"Background" moduleID:@"WuKongUsernameLogin"]];
        _bgImgView.frame = self.view.bounds;
    }
    return _bgImgView;
}

- (UILabel *)titleLbl {
    if(!_titleLbl) {
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:LLang(@"欢迎注册%@"),[WKApp shared].config.appName] attributes: @{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Semibold" size: 32],NSForegroundColorAttributeName: [UIColor colorWithRed:49/255.0 green:49/255.0 blue:49/255.0 alpha:1.0]}];
        _titleLbl = [[UILabel alloc] initWithFrame:CGRectMake(30, 83, WKScreenWidth-60, 50)];
        _titleLbl.attributedText = string;
        _titleLbl.textAlignment = NSTextAlignmentLeft;
    }
    return _titleLbl;
}
// ---------- 用户名输入 ----------

- (UILabel *)usernameLbl {
    if(!_usernameLbl) {
        _usernameLbl = [[UILabel alloc] init];
        _usernameLbl.text = LLang(@"账号");
        [_usernameLbl sizeToFit];
        _usernameLbl.lim_left = 20.0f;
        _usernameLbl.lim_centerY_parent = self.usernameBoxView;
    }
    return _usernameLbl;
}

- (UIView *)usernameBoxView {
    if(!_usernameBoxView) {
        _usernameBoxView = [[UIView alloc] initWithFrame:CGRectMake(0, 190.0f, WKScreenWidth, 40.0f)];
        //[_usernameBoxView setBackgroundColor:[UIColor redColor]];
    }
    return _usernameBoxView;
}

-(UITextField*) usernameTextField {
    if(!_usernameTextField) {
        CGFloat left = self.usernameLbl.lim_right +  10.0f;
        _usernameTextField = [[UITextField alloc] initWithFrame:CGRectMake(left, self.usernameBoxView.lim_height/2.0f - 20.0f, WKScreenWidth - left - 20.0f, 40.0f)];
        _usernameTextField.placeholder = LLang(@"请输入用户名");
    }
    return _usernameTextField;
}

- (UIView *)usernameBottomLineView {
    if(!_usernameBottomLineView) {
        _usernameBottomLineView = [[UIView alloc] initWithFrame:CGRectMake(20.0f, self.usernameBoxView.lim_height, WKScreenWidth-40.0f, 1)];
        _usernameBottomLineView.layer.backgroundColor = [WKApp shared].config.lineColor.CGColor;
    }
    return _usernameBottomLineView;
}


// ---------- 密码输入 ----------

- (UILabel *)passwordLbl {
    if(!_passwordLbl) {
        _passwordLbl = [[UILabel alloc] init];
        _passwordLbl.text = LLang(@"密码");
        [_passwordLbl sizeToFit];
        _passwordLbl.lim_left = 20.0f;
        _passwordLbl.lim_centerY_parent = self.passwordBoxView;
    }
    return _passwordLbl;
}

- (UIView *)passwordBoxView {
    if(!_passwordBoxView) {
        _passwordBoxView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, self.usernameBoxView.lim_bottom+20.0f, WKScreenWidth, self.usernameBoxView.lim_height)];
       // [_passwordBoxView setBackgroundColor:[UIColor grayColor]];
    }
    return _passwordBoxView;
}
- (UIView *)passwordBottomLineView {
    if(!_passwordBottomLineView) {
        _passwordBottomLineView = [[UIView alloc] initWithFrame:CGRectMake(20.0f, self.passwordBoxView.lim_height, WKScreenWidth-40.0f, 1)];
        _passwordBottomLineView.layer.backgroundColor = [WKApp shared].config.lineColor.CGColor;
    }
    return _passwordBottomLineView;
}

- (UITextField *)passwordTextField {
    if(!_passwordTextField) {
        CGFloat left = self.passwordLbl.lim_right +  10.0f;
        _passwordTextField = [[UITextField alloc] initWithFrame:CGRectMake(left, self.usernameBoxView.lim_height/2.0f - 20.0f, WKScreenWidth-20 - left, 40.0f)];
        [_passwordTextField setPlaceholder:LLang(@"请输入登录密码")];
        _passwordTextField.returnKeyType = UIReturnKeyDone;
        _passwordTextField.secureTextEntry = YES;
        _passwordTextField.delegate = self;
        
    }
    return _passwordTextField;
}
- (UIButton *)eyeBtn {
    if(!_eyeBtn) {
        CGFloat width = 32.0f;
        CGFloat height = 32.0f;
        _eyeBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.lim_width - 20.0f - width, self.passwordBoxView.lim_height/2.0f - (height)/2.0f, width, height)];
        [_eyeBtn setImage:[[WKApp shared] loadImage:@"BtnEyeOff" moduleID:@"WuKongUsernameLogin"] forState:UIControlStateNormal];
        [_eyeBtn setImage:[[WKApp shared] loadImage:@"BtnEyeOn" moduleID:@"WuKongUsernameLogin"] forState:UIControlStateSelected];
        _eyeBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_eyeBtn setImageEdgeInsets:UIEdgeInsetsMake(height/4.0f, width, height/4.0f,  width)];
        [_eyeBtn addTarget:self action:@selector(passwordLookPressed:) forControlEvents:UIControlEventTouchUpInside];
       // [_eyeBtn setBackgroundColor:[UIColor redColor]];
    }
    return _eyeBtn;
}

// ---------- 昵称输入 ----------

- (UILabel *)nicknameLbl {
    if(!_nicknameLbl) {
        _nicknameLbl = [[UILabel alloc] init];
        _nicknameLbl.text = LLang(@"昵称");
        [_nicknameLbl sizeToFit];
        _nicknameLbl.lim_left = 20.0f;
        _nicknameLbl.lim_centerY_parent = self.nicknameBoxView;
    }
    return _nicknameLbl;
}

- (UITextField *)nicknameTextField {
    if(!_nicknameTextField) {
        CGFloat left = self.nicknameLbl.lim_right +  10.0f;
        _nicknameTextField = [[UITextField alloc] initWithFrame:CGRectMake(left, self.nicknameBoxView.lim_height/2.0f - 20.0f, WKScreenWidth-20*2 - 32.0f, 40.0f)];
        _nicknameTextField.placeholder = LLang(@"请输入昵称");
    }
    return _nicknameTextField;
}

- (UIView *)nicknameBoxView {
    if(!_nicknameBoxView) {
        _nicknameBoxView = [[UIView alloc] initWithFrame:CGRectMake(0, self.passwordBoxView.lim_bottom + 20.0f, WKScreenWidth, self.usernameBoxView.lim_height)];
    }
    return _nicknameBoxView;
}

- (UIView *)nicknameBottomLineView {
    if(!_nicknameBottomLineView) {
        _nicknameBottomLineView = [[UIView alloc] initWithFrame:CGRectMake(20.0f, self.nicknameBoxView.lim_height, WKScreenWidth-40.0f, 1)];
        _nicknameBottomLineView.layer.backgroundColor = [WKApp shared].config.lineColor.CGColor;
    }
    return _nicknameBottomLineView;
}


// ---------- 底部相关 ----------


// 注册
- (UIButton *)registerBtn {
    if(!_registerBtn) {
        _registerBtn = [[UIButton alloc] initWithFrame:CGRectMake(30.0f, self.passwordBoxView.lim_bottom+82.0f, WKScreenWidth - 60.0f, 40.0f)];
        [_registerBtn setBackgroundColor:[WKApp shared].config.themeColor];
        [_registerBtn setTitle:LLang(@"注册") forState:UIControlStateNormal];
        [_registerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _registerBtn.layer.masksToBounds = YES;
        _registerBtn.layer.cornerRadius = 4.0f;
        [_registerBtn addTarget:self action:@selector(registerBtnPressed) forControlEvents:UIControlEventTouchUpInside];
        
        [WKApp.shared.config setThemeStyleButton:_registerBtn];
        
    }
    return _registerBtn;
}

-(UILabel*) loginTipLbl {
    if(!_loginTipLbl) {
        _loginTipLbl = [[UILabel alloc] init];
        [_loginTipLbl setText:LLang(@"已有账号？请")];
        [_loginTipLbl setFont:[UIFont systemFontOfSize:16.0f]];
        [_loginTipLbl setTextColor:[UIColor colorWithRed:153.0f/255.0f green:153.0f/255.0f blue:153.0f/255.0f alpha:1.0]];
        [_loginTipLbl sizeToFit];
        _loginTipLbl.lim_top = self.registerBtn.lim_bottom + 25.0f;
        _loginTipLbl.lim_left = self.view.lim_width/2.0f - _loginTipLbl.lim_width/2.0f - 20.0f;
    }
    return _loginTipLbl;
}

- (UIButton *)toLoginBtn {
    if(!_toLoginBtn) {
        _toLoginBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.loginTipLbl.lim_right, self.loginTipLbl.lim_top-7.2f, 20.0f, 22.0f)];
        [_toLoginBtn setTitle:LLang(@"登录") forState:UIControlStateNormal];
        [_toLoginBtn sizeToFit];
        [_toLoginBtn setTitleColor:[WKApp shared].config.themeColor forState:UIControlStateNormal];
        [[_toLoginBtn titleLabel] setFont:[UIFont systemFontOfSize:16.0f]];
        [_toLoginBtn addTarget:self action:@selector(toLoginPressed) forControlEvents:UIControlEventTouchUpInside];
    }
    return _toLoginBtn;
}

#pragma mark - 事件
// 跳到注册页面
-(void) toLoginPressed{
    [[WKNavigationManager shared] popViewControllerAnimated:YES];
}

// 密码那个小眼睛点击
-(void) passwordLookPressed:(UIButton*)btn {
    btn.selected = !btn.selected;
    _passwordTextField.secureTextEntry = !btn.selected;
}
// 国家点击
-(void) countryBtnPressed {
    
}

-(void) registerBtnPressed {
    NSString *username = self.usernameTextField.text;
    NSString *password = self.passwordLbl.text;
    NSString *nickname = self.nicknameLbl.text;
    UIView *topView = WKNavigationManager.shared.topViewController.view;
     if(!username || username.length == 0) {
         [topView showHUDWithHide:LLang(@"账号不能为空！")];
         return;
     }
     if(!password || password.length == 0) {
         [topView showHUDWithHide:LLang(@"密码不能为空！")];
         return;
     }
     if(!nickname || nickname.length == 0) {
         [topView showHUDWithHide:LLang(@"昵称不能为空！")];
         return;
     }
     [topView showHUD];
     [WKAPIClient.sharedClient POST:@"user/usernameregister" parameters:@{
         @"username": username,
         @"password": password,
         @"name": nickname,
     }].then(^(NSDictionary *result){
         [topView hideHud];
         
         WKLoginResp *resp = (WKLoginResp*)[WKLoginResp fromMap:result[@"data"] type:ModelMapTypeAPI];
         
         [WKUsernameLoginVM handleLoginData:resp isSave:NO];
        
         WKMnemonicsBackupVC *vc = [WKMnemonicsBackupVC new];
         [WKNavigationManager.shared pushViewController:vc animated:YES];
     }).catch(^(NSError *error){
         [topView switchHUDError:error.domain];
     });
   
}

- (M80AttributedLabel *)privacyLbl {
    if(!_privacyLbl) {
        CGFloat bottom = 0.0f;
        if (@available(iOS 11.0, *)) {
             bottom = [UIApplication sharedApplication].keyWindow.safeAreaInsets.bottom;
        }
        _privacyLbl = [[M80AttributedLabel alloc] init];
        _privacyLbl.delegate = self;
        _privacyLbl.backgroundColor = [UIColor clearColor];
        [_privacyLbl setFont:[UIFont systemFontOfSize:12.0f]];
        [_privacyLbl setTextColor:[WKApp shared].config.tipColor];
        [_privacyLbl appendText:LLang(@"点击“注册”即表示已阅读并同意")];
        NSString *uPTxt = LLang(@"用户协议");
        [_privacyLbl addCustomLink:[WKApp shared].config.userAgreementUrl forRange:NSMakeRange(_privacyLbl.text.length, uPTxt.length)];
        [_privacyLbl appendText:uPTxt];
        [_privacyLbl appendText:@"、"];
        NSString *pPTxt = LLang(@"隐私政策");
        [_privacyLbl addCustomLink:[WKApp shared].config.privacyAgreementUrl forRange:NSMakeRange(_privacyLbl.text.length, pPTxt.length)];
        [_privacyLbl appendText:pPTxt];
        
        [_privacyLbl sizeToFit];
        _privacyLbl.lim_centerX_parent = self.view;
        _privacyLbl.lim_top = WKScreenHeight - ( bottom + 30.0f);
    }
    return _privacyLbl;
}

#pragma mark -- M80AttributedLabelDelegate

- (void)m80AttributedLabel:(M80AttributedLabel *)label clickedOnLink:(id)linkData {
    WKWebViewVC *vc = [WKWebViewVC new];
    vc.url = [NSURL URLWithString:linkData];
    [[WKNavigationManager shared] pushViewController:vc animated:YES];
}

#pragma mark -- 委托
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    return true;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if(_passwordTextField == textField) {
       
    }
    return YES;
}
- (void)dealloc {
    
}

@end
